﻿using System.Linq.Expressions;
using Basic.UserModel.DB;
using Basic.UserRemoteModel.User.Model;
using LinqKit;
using SqlSugar;
using WeDonekRpc.Helper;

namespace Basic.UserRepository.Linq
{
    internal static class UserLinq
    {
        public static Expression<Func<DBUserInfo, bool>> ToWhere (this UserQueryParam query)
        {
            ExpressionStarter<DBUserInfo> where = PredicateBuilder.New<DBUserInfo>();
            if (query.Sex.HasValue)
            {
                where = where.And(c => c.Sex == query.Sex.Value);
            }
            if (!query.UserState.IsNull())
            {
                where = where.And(c => query.UserState.Contains(c.UserState));
            }
            if (!query.RegMode.IsNull())
            {
                where = where.And(c => c.RegMode == query.RegMode);
            }
            if (query.RegBegin.HasValue && query.RegEnd.HasValue)
            {
                where = where.And(c => SqlFunc.Between(c.RegTime, query.RegBegin.Value, query.RegEnd.Value));
            }
            else if (query.RegBegin.HasValue)
            {
                where = where.And(c => c.RegTime >= query.RegBegin.Value);
            }
            else if (query.RegEnd.HasValue)
            {
                where = where.And(c => c.RegTime <= query.RegEnd.Value);
            }
            if (query.LoginBegin.HasValue && query.LoginEnd.HasValue)
            {
                where = where.And(c => SqlFunc.Between(c.LastLoginDate, query.LoginBegin.Value, query.LoginEnd.Value));
            }
            else if (query.LoginBegin.HasValue)
            {
                where = where.And(c => c.LastLoginDate >= query.LoginBegin.Value);
            }
            else if (query.LoginEnd.HasValue)
            {
                where = where.And(c => c.LastLoginDate <= query.LoginEnd.Value);
            }
            if (query.QueryKey.IsNotNull())
            {
                where = where.And(c => c.NickName.Contains(query.QueryKey));
            }
            if (where.IsStarted)
            {
                return where;
            }
            return null;
        }
    }
}
